package com.twu.biblioteca;

import com.twu.biblioteca.command.Command;
import com.twu.biblioteca.command.CommandName;

import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: zgq
 * Date: 13-6-23
 * Time: 下午1:31
 * To change this template use File | Settings | File Templates.
 */
public class Controller {
    private static ArrayList<CommandName> commandList = new ArrayList<CommandName>();
    private static ArrayList<CommandName> commandListBeforeLogin = new ArrayList<CommandName>();

    private static final String INVALID_OPTION_NOTICE = "Select a valid option!!";
    private static final String HEADLINE = "Please select an option by input number:";
    private static final String COMMAND_PACKAGE = "com.twu.biblioteca.command.";
    private BibliotecaDataOperator bibliotecaDataOperator;

    public Controller() {
        bibliotecaDataOperator = new BibliotecaDataOperator();
    }

    static {
        commandList.add(CommandName.BOOK_LIST);
        commandList.add(CommandName.RESERVE_BOOK);
        commandList.add(CommandName.MEMBERSHIP);
        commandList.add(CommandName.MOVIE_LIST);
        commandList.add(CommandName.QUIT);
        commandListBeforeLogin.add(CommandName.BOOK_LIST);
        commandListBeforeLogin.add(CommandName.MEMBERSHIP);
        commandListBeforeLogin.add(CommandName.MOVIE_LIST);
        commandListBeforeLogin.add(CommandName.LOGIN);
        commandListBeforeLogin.add(CommandName.QUIT);
    }

    public boolean contains(CommandName command) {
        return getCommandList().contains(command);
    }

    public boolean contains(int commandIndex) {
        return commandIndex >0 && commandIndex <= getCommandList().size();
    }

    private ArrayList<CommandName> getCommandList() {
        if(bibliotecaDataOperator.getSession() == null) return commandListBeforeLogin;
        return commandList;
    }

    public String execute(int choice) {
        if(choice>=1&&choice<=getCommandList().size()) {
            return execute(getCommandList().get(choice - 1));
        }
        return INVALID_OPTION_NOTICE;
    }

    public String execute(CommandName commandName) {
        Command command = null;
        try {
            command = (Command) Class.forName(COMMAND_PACKAGE +commandName.getExecuteClassName()).newInstance();
            return command.exucute(bibliotecaDataOperator);
        } catch (Exception e) {
            e.printStackTrace();
            return INVALID_OPTION_NOTICE;
        }
    }

    public String printStartInfo() {
        ArrayList<CommandName> commandList = getCommandList();
        String startInfo = HEADLINE + "\n";
        for (int index = 0; index<commandList.size(); index++)
            startInfo += (index+1) +":" + commandList.get(index) + "\t";
        return startInfo;
    }

}
